package com.example.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
@MapperScan(value={"com.example.mapper.*"})
public class MybatisPlusSaasConfig {

    private static final List<String> tenantTable = new ArrayList<String>();
    private static final List<String> noTenantTable = new ArrayList<String>();

    //要走租户逻辑的表
    static {
        tenantTable.add("device_info");
    }

    //不走租户逻辑的表
    static {
        noTenantTable.add("sys_user");
    }
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
            @Override
            public String getTenantIdColumn() {
                return "tenant_id";
            }

            @Override
            public Expression getTenantId() {
                return new LongValue(TenantContext.getTenant());
            }

            // 返回 true 表示不走租户逻辑
            @Override
            public boolean ignoreTable(String tableName) {
                if (noTenantTable.contains(tableName)) {
                    return true;
                }
                return false;
            }
        }));
        return interceptor;
    }
}
